package com.netease.nie.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.netease.nie.base.controllers.BaseController;
import com.netease.nie.base.exceptions.BusinessException;
import com.netease.nie.constants.BusinessConstants;
import com.netease.nie.dto.ExchangeGoodsExchangeDto;
import com.netease.nie.dto.MyExchangeDto;
import com.netease.nie.facade.ExchangeGoodsFacade;
import com.netease.nie.facade.MyExchangeFacade;

/**
 * 我的兑换管理
 * 
 * @author Derek Xu
 * @CreateDate Jul 12, 2016
 */
@RestController
@RequestMapping("/api/user")
public class ExchangeController extends BaseController {
	@Autowired
	private ExchangeGoodsFacade exchangeGoodsFacade;

	@Autowired
	private MyExchangeFacade myExchangeFacade;

	/**
	 * 兑换结果接口
	 * 
	 * @param goodsId
	 * @param ownerId
	 * @param exchangeCodeId
	 * @return
	 */
	@RequestMapping(value = "/exchange_result", method = RequestMethod.GET, produces = "application/json")
	public String exchangeResult(HttpServletRequest request,
			@RequestParam(value = "order_id") Long orderId) {
		Long userId = (Long) request.getAttribute("userId");
		if (userId == null)
			jsonFail(BusinessConstants.USER_NOT_LOGIN.getCode(),
					"用户未登录");
		if (userId <= 0)
			throw new BusinessException(
					BusinessConstants.INVALID_USER_ID.getCode(),
					"用户id不合法");
		if (orderId <= 0 || orderId == null)
			throw new BusinessException(
					BusinessConstants.ORDER_NOT_EXISTS.getCode(),
					"订单id不合法");

		ExchangeGoodsExchangeDto exchangeGoodsExchangeDto = exchangeGoodsFacade.queryGoodsExchangeDtoById(orderId, userId);
		
		return jsonSuccess(exchangeGoodsExchangeDto);
	}

	/**
	 * 我的兑换接口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exchanged", method = RequestMethod.GET, produces = "application/json") 
	public String myExchange(HttpServletRequest request,
			@RequestParam(value = "page") Integer page,
			@RequestParam(value = "page_size") Integer pageSize) {
		Long userId = (Long) request.getAttribute("userId");
		if (userId == null)
			throw new BusinessException(
					BusinessConstants.USER_NOT_LOGIN.getCode(),
					"用户未登录");
		if (userId <= 0)
			throw new BusinessException(
					BusinessConstants.INVALID_USER_ID.getCode(),
					"用户id不合法");
		
		List<MyExchangeDto> myExchangeDtoList = myExchangeFacade
				.listMyExchangeByUserId(userId, page, pageSize);

		return jsonSuccess(myExchangeDtoList);
	}
}
